/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */
package com.hopes.bizz.risk.control.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopes.bizz.risk.control.dto.RiskMeasureTaskConfigDTO;
import com.hopes.bizz.risk.control.entity.RiskControlMeasureEntity;
import com.hopes.bizz.risk.control.entity.RiskMeasureTaskConfigEntity;
import com.hopes.bizz.risk.control.entity.RiskMeasureTaskEntity;
import com.hopes.bizz.risk.control.mapper.RiskControlMeasureMapper;
import com.hopes.bizz.risk.control.mapper.RiskMeasureTaskConfigMapper;
import com.hopes.bizz.risk.control.service.RiskMeasureTaskConfigService;
import com.hopes.bizz.risk.control.service.RiskMeasureTaskService;
import com.hopes.bizz.risk.control.vo.RiskMeasureTaskConfigVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 隐患排查内容配置
 *
 * @author pig
 * @date 2023-07-20 08:56:11
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RiskMeasureTaskConfigServiceImpl extends ServiceImpl<RiskMeasureTaskConfigMapper, RiskMeasureTaskConfigEntity> implements RiskMeasureTaskConfigService {

    private final RiskMeasureTaskService riskMeasureTaskService;
    private final RiskControlMeasureMapper riskControlMeasureMapper;

    @Override
    public RiskMeasureTaskConfigVO getById(Serializable id) {
        final RiskMeasureTaskConfigVO measureTaskConfigVO = new RiskMeasureTaskConfigVO();
        final RiskMeasureTaskConfigEntity measureTaskConfigEntity = this.baseMapper.selectById(id);
        if (null != measureTaskConfigEntity) {
            BeanUtils.copyProperties(measureTaskConfigEntity, measureTaskConfigVO);
            final LambdaQueryWrapper<RiskMeasureTaskEntity> wrapper = Wrappers.<RiskMeasureTaskEntity>lambdaQuery()
                    .eq(RiskMeasureTaskEntity::getRiskTaskConfigId, measureTaskConfigEntity.getId());
            measureTaskConfigVO.setRiskMeasureTaskList(riskMeasureTaskService.list(wrapper));
        }
        return measureTaskConfigVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(RiskMeasureTaskConfigDTO measureTaskConfigDTO) {
        final RiskControlMeasureEntity controlMeasureEntity = riskControlMeasureMapper.selectById(measureTaskConfigDTO.getRiskControlId());
        if (null == controlMeasureEntity) {
            throw new IllegalArgumentException("所属管控措施获取失败！");
        }
        final RiskMeasureTaskConfigEntity taskConfigEntity = new RiskMeasureTaskConfigEntity();
        taskConfigEntity.setRiskControlId(controlMeasureEntity.getId());
        taskConfigEntity.setRiskUnitId(controlMeasureEntity.getRiskUnitId());
        taskConfigEntity.setRiskEventId(controlMeasureEntity.getRiskEventId());
        taskConfigEntity.setCheckContent(measureTaskConfigDTO.getCheckContent());
        this.baseMapper.insert(taskConfigEntity);
        // 批量新增隐患排查任务
        riskMeasureTaskService.batchSaveWithTaskConfig(taskConfigEntity, measureTaskConfigDTO.getRiskMeasureTaskList());
        log.debug("新增隐患检查任务配置，新增检查任务数量：{}", measureTaskConfigDTO.getRiskMeasureTaskList().size());
        return true;
    }

    @Override
    public boolean saveBatchByVO(List<RiskMeasureTaskConfigVO> riskMeasureTaskConfigVOList) {
        if (CollectionUtil.isEmpty(riskMeasureTaskConfigVOList)) {
            return false;
        }
        // 1、批量保存管控措施配置
        baseMapper.batchSaveByVO(riskMeasureTaskConfigVOList);
        // 2、批量管控措施任务
        final List<RiskMeasureTaskEntity> riskMeasureTaskList = new ArrayList<>();
        for (RiskMeasureTaskConfigVO measureTaskConfigVO : riskMeasureTaskConfigVOList) {
            final List<RiskMeasureTaskEntity> taskList = measureTaskConfigVO.getRiskMeasureTaskList();
            if (CollectionUtil.isEmpty(taskList)) {
                continue;
            }
            taskList.forEach(item -> {
                item.setRiskTaskConfigId(measureTaskConfigVO.getId());
                item.setRiskUnitId(measureTaskConfigVO.getRiskUnitId());
                item.setRiskEventId(measureTaskConfigVO.getRiskEventId());
                item.setRiskControlId(measureTaskConfigVO.getRiskControlId());
                item.setCheckContent(measureTaskConfigVO.getCheckContent());
            });
            riskMeasureTaskList.addAll(taskList);
        }
        if (CollectionUtil.isNotEmpty(riskMeasureTaskList)) {
            riskMeasureTaskService.saveBatch(riskMeasureTaskList);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(RiskMeasureTaskConfigDTO measureTaskConfigDTO) {
        final RiskMeasureTaskConfigEntity param = new RiskMeasureTaskConfigEntity();
        param.setId(measureTaskConfigDTO.getId());
        param.setCheckContent(measureTaskConfigDTO.getCheckContent());
        this.baseMapper.updateById(param);

        // 处理对应的隐患排查任务
        if (CollectionUtil.isEmpty(measureTaskConfigDTO.getRiskMeasureTaskList())) {
            return true;
        }
        final List<RiskMeasureTaskEntity> riskMeasureTaskList = measureTaskConfigDTO.getRiskMeasureTaskList();
        final List<RiskMeasureTaskEntity> insertTaskList = new ArrayList<>();
        final List<RiskMeasureTaskEntity> updateTaskList = new ArrayList<>();

        riskMeasureTaskList.forEach((item) -> {
            if (Objects.isNull(item.getId())) {
                insertTaskList.add(item);
            } else {
                updateTaskList.add(item);
            }
        });

        if (CollectionUtil.isNotEmpty(insertTaskList)) {
            final RiskMeasureTaskConfigEntity taskConfigEntity = baseMapper.selectById(measureTaskConfigDTO.getId());
            riskMeasureTaskService.batchSaveWithTaskConfig(taskConfigEntity, insertTaskList);
            log.debug("更新隐患检查任务配置，新增检查任务数量：{}", insertTaskList.size());
        }
        if (CollectionUtil.isNotEmpty(updateTaskList)) {
            final List<RiskMeasureTaskEntity> collect = updateTaskList.stream().peek(e -> e.setCheckContent(measureTaskConfigDTO.getCheckContent())).collect(Collectors.toList());
            riskMeasureTaskService.updateBatchById(collect);
            log.debug("更新隐患检查任务配置，更新检查任务数量：{}", collect.size());
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeBatchByIds(Collection<?> list) {
        if (CollUtil.isEmpty(list)) {
            return true;
        }
        final List<RiskMeasureTaskEntity> riskMeasureTaskList = riskMeasureTaskService.list(Wrappers.<RiskMeasureTaskEntity>lambdaQuery().in(RiskMeasureTaskEntity::getRiskTaskConfigId, list));
        if (CollUtil.isNotEmpty(riskMeasureTaskList)) {
            riskMeasureTaskService.removeBatchByIds(riskMeasureTaskList.stream().map(RiskMeasureTaskEntity::getId).collect(Collectors.toList()));
        }
        return baseMapper.deleteBatchIds(list) > 0;
    }

    @Override
    public Long countByRiskUnitIdList(List<Long> riskUnitIdList) {
        if (CollectionUtil.isEmpty(riskUnitIdList)) {
            return 0L;
        }
        return this.baseMapper.countByRiskUnitIdList(riskUnitIdList).getCount();
    }
}
